package timetracker.client.forms;

import timetracker.client.ContragentService;
import timetracker.client.ContragentServiceAsync;
import timetracker.client.database.Contragent;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;

public class ContragentForm extends DialogBox {

	private static ContragentFormUiBinder uiBinder = GWT
			.create(ContragentFormUiBinder.class);
	@UiField TextBox Name;
	@UiField Button btnOK;
	@UiField Button btnCancel;

	interface ContragentFormUiBinder extends UiBinder<Widget, ContragentForm> {
	}
	
	private Contragent contragent = new Contragent();
	
	public Contragent getContragent(){
		return contragent;
	}
	
	public void setContragent(Contragent contragent){
		this.contragent = contragent;
	}
	
	private final ContragentServiceAsync contragentService = GWT.create(ContragentService.class);
	AsyncCallback<Contragent> callback = new AsyncCallback<Contragent>() {

		@Override
		public void onFailure(Throwable caught) {
			String details = caught.getMessage();
			Window.alert(details);
		}

		@Override
		public void onSuccess(Contragent retContragent) {
			contragent = retContragent;
			Window.alert("OK: " + contragent.getKey() + " " + contragent.getName());
		}
	};

	
	private void initForm(){
		setWidget(uiBinder.createAndBindUi(this));
		setText("Edit contragent");
	}
	
	protected void onLoad(){
		Name.setText(contragent.getName());
	}
	
	public ContragentForm() {
		initForm();
	}

	/*public ContragentForm(Contragent contragent) {
		initForm();
		
		Name.setText("New contragent");
	}*/

	
	@UiHandler("btnOK")
	void onBtnOKClick(ClickEvent event) {
		contragent.setName(Name.getText());
		contragentService.contragentSave(contragent, callback);
		hide();
	}
	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent event) {
		hide();
	}
}